{% extends "base.html" %}

{% block title %}环境管理 - API场景组合测试工具{% endblock %}

{% block head %}
<style>
    .env-card {
        transition: all 0.3s ease;
    }
    .env-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    }
    .variable-table {
        max-height: 200px;
        overflow-y: auto;
    }
</style>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-server"></i> 环境管理</h2>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEnvModal">
        <i class="fas fa-plus"></i> 添加环境
    </button>
</div>

<!-- 环境列表 -->
<div class="row" id="env-list" data-environments="{{ environments|tojson }}">
    {% for env in environments %}
    <div class="col-md-4 mb-4">
        <div class="card env-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">{{ env.name }}</h5>
                <div class="dropdown">
                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="dropdownMenuButton{{ env.id }}" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-ellipsis-v"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenuButton{{ env.id }}">
                        <li><a class="dropdown-item edit-env" href="#" data-id="{{ env.id }}"><i class="fas fa-edit"></i> 编辑</a></li>
                        <li><a class="dropdown-item clone-env" href="#" data-id="{{ env.id }}"><i class="fas fa-copy"></i> 复制</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item text-danger delete-env" href="#" data-id="{{ env.id }}"><i class="fas fa-trash"></i> 删除</a></li>
                    </ul>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <strong>基础URL：</strong> {{ env.base_url }}
                </div>
                <div class="mb-3">
                    <strong>描述：</strong> 
                    <p class="text-muted">{{ env.description or '无描述' }}</p>
                </div>
                <div class="mb-3">
                    <strong>环境变量：</strong>
                    <div class="variable-table">
                        <table class="table table-sm table-bordered">
                            <thead>
                                <tr>
                                    <th>变量名</th>
                                    <th>值</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for var in env.variables %}
                                <tr>
                                    <td>{{ var.name }}</td>
                                    <td>{{ var.value }}</td>
                                </tr>
                                {% else %}
                                <tr>
                                    <td colspan="2" class="text-center">无环境变量</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="card-footer text-muted">
                <small>创建时间: {{ env.created_at }}</small>
            </div>
        </div>
    </div>
    {% else %}
    <div class="col-12">
        <div class="alert alert-info" role="alert">
            <i class="fas fa-info-circle"></i> 暂无环境配置，请点击"添加环境"按钮创建新环境。
        </div>
    </div>
    {% endfor %}
</div>

<!-- 添加/编辑环境模态框 -->
<div class="modal fade" id="addEnvModal" tabindex="-1" aria-labelledby="addEnvModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addEnvModalLabel">添加环境</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="envForm">
                    <input type="hidden" id="envId" name="id">
                    <div class="mb-3">
                        <label for="envName" class="form-label">环境名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="envName" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="baseUrl" class="form-label">基础URL <span class="text-danger">*</span></label>
                        <input type="url" class="form-control" id="baseUrl" name="base_url" placeholder="https://api.example.com" required>
                    </div>
                    <div class="mb-3">
                        <label for="envDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="envDescription" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">全局请求头</label>
                        <div id="headerContainer">
                            <div class="row mb-2 header-row">
                                <div class="col-5">
                                    <input type="text" class="form-control" name="header_names[]" placeholder="Header名称">
                                </div>
                                <div class="col-6">
                                    <input type="text" class="form-control" name="header_values[]" placeholder="Header值">
                                </div>
                                <div class="col-1">
                                    <button type="button" class="btn btn-outline-danger btn-sm remove-header">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-outline-secondary btn-sm mt-2" id="addHeader">
                            <i class="fas fa-plus"></i> 添加请求头
                        </button>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">环境变量</label>
                        <div id="variableContainer">
                            <div class="row mb-2 variable-row">
                                <div class="col-5">
                                    <input type="text" class="form-control" name="var_names[]" placeholder="变量名">
                                </div>
                                <div class="col-6">
                                    <input type="text" class="form-control" name="var_values[]" placeholder="变量值">
                                </div>
                                <div class="col-1">
                                    <button type="button" class="btn btn-outline-danger btn-sm remove-variable">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-outline-secondary btn-sm mt-2" id="addVariable">
                            <i class="fas fa-plus"></i> 添加变量
                        </button>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEnv">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteEnvModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除环境 <strong id="deleteEnvName"></strong> 吗？此操作不可恢复。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDelete">删除</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    $(document).ready(function() {
        // 添加请求头行
        $('#addHeader').click(function() {
            const headerRow = `
                <div class="row mb-2 header-row">
                    <div class="col-5">
                        <input type="text" class="form-control" name="header_names[]" placeholder="Header名称">
                    </div>
                    <div class="col-6">
                        <input type="text" class="form-control" name="header_values[]" placeholder="Header值">
                    </div>
                    <div class="col-1">
                        <button type="button" class="btn btn-outline-danger btn-sm remove-header">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            $('#headerContainer').append(headerRow);
        });
        
        // 添加变量行
        $('#addVariable').click(function() {
            const variableRow = `
                <div class="row mb-2 variable-row">
                    <div class="col-5">
                        <input type="text" class="form-control" name="var_names[]" placeholder="变量名">
                    </div>
                    <div class="col-6">
                        <input type="text" class="form-control" name="var_values[]" placeholder="变量值">
                    </div>
                    <div class="col-1">
                        <button type="button" class="btn btn-outline-danger btn-sm remove-variable">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
            $('#variableContainer').append(variableRow);
        });
        
        // 删除行
        $(document).on('click', '.remove-header', function() {
            $(this).closest('.header-row').remove();
        });
        
        $(document).on('click', '.remove-variable', function() {
            $(this).closest('.variable-row').remove();
        });
        
        // 编辑环境
        $('.edit-env').click(function(e) {
            e.preventDefault();
            const envId = $(this).data('id');
            
            // 通过AJAX获取环境详情
            $.get(`/environment/${envId}`, function(data) {
                console.log("data:",data)
                $('#envId').val(data.id);
                $('#envName').val(data.name);
                $('#baseUrl').val(data.base_url);
                $('#envDescription').val(data.description);
                
                //清空现有行
                $('#headerContainer').empty();
                $('#variableContainer').empty();
                
                // 添加请求头
                if (data.headers && data.headers.length > 0) {
                    data.headers.forEach(function(header) {
                        const headerRow = `
                            <div class="row mb-2 header-row">
                                <div class="col-5">
                                    <input type="text" class="form-control" name="header_names[]" value="${header.name}" placeholder="Header名称">
                                </div>
                                <div class="col-6">
                                    <input type="text" class="form-control" name="header_values[]" value="${header.value}" placeholder="Header值">
                                </div>
                                <div class="col-1">
                                    <button type="button" class="btn btn-outline-danger btn-sm remove-header">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                        $('#headerContainer').append(headerRow);
                    });
                } else {
                    // 添加一个空行
                    $('#addHeader').click();
                }
                
                // 添加变量
                if (data.variables && data.variables.length > 0) {
                    data.variables.forEach(function(variable) {
                        const variableRow = `
                            <div class="row mb-2 variable-row">
                                <div class="col-5">
                                    <input type="text" class="form-control" name="var_names[]" value="${variable.name}" placeholder="变量名">
                                </div>
                                <div class="col-6">
                                    <input type="text" class="form-control" name="var_values[]" value="${variable.value}" placeholder="变量值">
                                </div>
                                <div class="col-1">
                                    <button type="button" class="btn btn-outline-danger btn-sm remove-variable">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                        $('#variableContainer').append(variableRow);
                    });
                } else {
                    // 添加一个空行
                    $('#addVariable').click();
                }
                
                // 更改模态框标题
                $('#addEnvModalLabel').text('编辑环境');
                $('#addEnvModal').modal('show');
            });
        });
        
        // 复制环境
        $('.clone-env').click(function(e) {
            e.preventDefault();
            const envId = $(this).data('id');
            
            // 通过AJAX获取环境详情
            $.get(`/environment/${envId}`, function(data) {
                $('#envId').val(''); // 清空ID，表示新建
                $('#envName').val(data.name + ' (复制)');
                $('#baseUrl').val(data.base_url);
                $('#envDescription').val(data.description);
                
                // 清空现有行
                $('#headerContainer').empty();
                $('#variableContainer').empty();
                
                // 添加请求头
                if (data.headers && data.headers.length > 0) {
                    data.headers.forEach(function(header) {
                        const headerRow = `
                            <div class="row mb-2 header-row">
                                <div class="col-5">
                                    <input type="text" class="form-control" name="header_names[]" value="${header.name}" placeholder="Header名称">
                                </div>
                                <div class="col-6">
                                    <input type="text" class="form-control" name="header_values[]" value="${header.value}" placeholder="Header值">
                                </div>
                                <div class="col-1">
                                    <button type="button" class="btn btn-outline-danger btn-sm remove-header">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                        $('#headerContainer').append(headerRow);
                    });
                } else {
                    // 添加一个空行
                    $('#addHeader').click();
                }
                
                // 添加变量
                if (data.variables && data.variables.length > 0) {
                    data.variables.forEach(function(variable) {
                        const variableRow = `
                            <div class="row mb-2 variable-row">
                                <div class="col-5">
                                    <input type="text" class="form-control" name="var_names[]" value="${variable.name}" placeholder="变量名">
                                </div>
                                <div class="col-6">
                                    <input type="text" class="form-control" name="var_values[]" value="${variable.value}" placeholder="变量值">
                                </div>
                                <div class="col-1">
                                    <button type="button" class="btn btn-outline-danger btn-sm remove-variable">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                        $('#variableContainer').append(variableRow);
                    });
                } else {
                    // 添加一个空行
                    $('#addVariable').click();
                }
                
                // 更改模态框标题
                $('#addEnvModalLabel').text('复制环境');
                $('#addEnvModal').modal('show');
            });
        });
        
        // 打开添加环境模态框
        $('#addEnvModal').on('show.bs.modal', function(e) {
            if (!e.relatedTarget) return; // 如果是通过编辑按钮打开，则跳过
            
            // 重置表单
            $('#envForm')[0].reset();
            $('#envId').val('');
            $('#addEnvModalLabel').text('添加环境');
            
            // 清空现有行并添加一个空行
            $('#headerContainer').empty();
            $('#variableContainer').empty();
            $('#addHeader').click();
            $('#addVariable').click();
        });
        
        // 保存环境
        $('#saveEnv').click(function() {
            // 表单验证
            if (!$('#envForm')[0].checkValidity()) {
                $('#envForm')[0].reportValidity();
                return;
            }
            
            // 收集表单数据
            const envId = $('#envId').val();
            const formData = {
                name: $('#envName').val(),
                base_url: $('#baseUrl').val(),
                description: $('#envDescription').val(),
                headers: [],
                variables: []
            };
            
            // 收集请求头
            $('.header-row').each(function() {
                const name = $(this).find('input[name="header_names[]"]').val();
                const value = $(this).find('input[name="header_values[]"]').val();
                if (name && value) {
                    formData.headers.push({ name, value });
                }
            });
            
            // 收集变量
            $('.variable-row').each(function() {
                const name = $(this).find('input[name="var_names[]"]').val();
                const value = $(this).find('input[name="var_values[]"]').val();
                if (name && value) {
                    formData.variables.push({ name, value });
                }
            });
            
            // 发送请求
            const url = envId ? `/environment/${envId}` : '/environment/';
            const method = envId ? 'PUT' : 'POST';
            
            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    if (response.success) {
                        // 关闭模态框并刷新页面
                        $('#addEnvModal').modal('hide');
                        location.reload();
                    } else {
                        alert('保存失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        });
        
        // 删除环境
        $('.delete-env').click(function(e) {
            e.preventDefault();
            const envId = $(this).data('id');
            const envName = $(this).closest('.card').find('.card-header h5').text();
            
            $('#deleteEnvName').text(envName);
            $('#confirmDelete').data('id', envId);
            $('#deleteEnvModal').modal('show');
        });
        
        // 确认删除
        $('#confirmDelete').click(function() {
            const envId = $(this).data('id');
            
            $.ajax({
                url: `/environment/${envId}`,
                type: 'DELETE',
                success: function(response) {
                    if (response.success) {
                        // 关闭模态框并刷新页面
                        $('#deleteEnvModal').modal('hide');
                        location.reload();
                    } else {
                        alert('删除失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        });
    });
</script>
{% endblock %}